import { Order } from '../order/order-model.js';
import { Cart } from '../cart/cart-model.js';
import { Address } from '../../utils/address.js';

var order = new Order();
var cart = new Cart();
var address = new Address();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromCartFlag: true,
    addressInfo: null,
    hiddenBox:true,
    all_buy_total:0,
    amount:0,
    hiddenCoupon: true,
    couponList:{},  //当前显示的优惠券列表
    type : 1,
    onSub:false
  },

  onLoad: function (options){
    var flag = options.from && options.from;
    var cartId = options.id && options.id;
    this.data.flag = flag;
    this.data.cartId = cartId;
    if (flag=='cart'||flag=='buy'){//购物车或者直接购买时
      this.setData({
        orderStatus: 0
      })
    }
    if(flag=="cart"){
      this.data.type = 0;
    } else if (flag == "buy"){
      this.data.type = 1;
    }

    this._loadData(flag);
  },

  _loadData: function (flag){
    var that = this
    /*通过接口获取用户默认的收货地址*/
    address.getAddress((res) => {
      var params = {};
      if(res.status==1){
        var addressInfo = {
          id: res.items.id,
          name: res.items.userName,
          mobile: res.items.telNumber,
          totalDetail: address.setAddressInfo(res.items)
        };
        this.setData({
          addressInfo: addressInfo
        });
        var params = { "type": this.data.type, "address_id": res.items.id, "id": this.data.cartId }
      } else if (res.status == 0){
        var params = { "type": this.data.type, "id": this.data.cartId }
      }
      that.orderInfo(params);

    });

  },
  orderInfo: function (params){
    wx.showLoading({
      title: '加载中',
    })
    order.getOrdersToPay(params, (data) => {
      //获取购物车选定的商品信息（价格、数量、总价）
      wx.hideLoading();
      if(data.status != 1){
        wx.showModal({
          title: '提示',
          content: data.msg+'，请重新选择',
          confirmText:'重新选择',
          success(res) {
            if (res.confirm) {
              wx.navigateBack({ changed: true });//返回上一页
            } else if (res.cancel) {
              wx.navigateBack({ changed: true });//返回上一页
            }
          }
        })
        return false;
      }
      this.data.amount = data.amount;
      var itemList = data.items;
      var orderDatas = [];
      for (let i in itemList) {
        orderDatas.push(itemList[i]);
      }
      orderDatas = this._getCaculateShopTotal(orderDatas)
      /***保存期最初的数据，仅用于计算，始终不能改变该值，避免多次选择优惠券原始价格被覆盖***/
      orderDatas.forEach((item, index) => {
        item.shopTotal_orign = item.shopTotal;
      })
      this.data.amount_orign = data.amount;
      /********** */
      this.setData({
        orderTOPayData: orderDatas,
        amount: this.data.amount,
        scoreMoney: data.scoreMoney,
        all_buy_total: data.buy_total
      })
    })
  },
    /*修改或者添加地址信息*/
  editAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        if (res.telNumber) {
          //保存地址
          address.submitAddress(res, (data) => {
            var addressInfo = {
              id:data.items.id,
              name: res.userName,
              mobile: res.telNumber,
              totalDetail: address.setAddressInfo(res)
            };
            var params = { "type": that.data.type, "id": that.data.cartId, 'address_id': data.items.id}
            that.orderInfo(params);
            that.setData({
              addressInfo: addressInfo
            });     
          });
        }
      }
    })
  },

  //积分开关改变
  jifenSwitchChange:function(e){
    var status = e.detail.value;
    this.data.status = status;
    this._getCaculateAmount(status);
  },

  // 合计
  _getCaculateAmount: function (status) {
    if(status){
      this.data.amount = parseFloat(this.data.amount).toFixed(2) - parseFloat(this.data.scoreMoney).toFixed(2);

    }else{
      this.data.amount = (parseFloat(this.data.amount).toFixed(2)*100 + parseFloat(this.data.scoreMoney).toFixed(2)*100)/100;
    }
    this.setData({
      amount: this.data.amount
    })
  },

  // 小计
  _getCaculateShopTotal: function (orderDatas) {
    var len = orderDatas.length,
        total = 0;
    for (let i = 0; i < len; i++) {
      if (orderDatas[i].shipping_price==null){
        orderDatas[i].shipping_price = 0;
      }

      total = parseFloat(orderDatas[i].sale_real_total).toFixed(2)*100 + parseFloat(orderDatas[i].shipping_price).toFixed(2)*100 ;
      orderDatas[i].shopTotal = total/100;
    }
    return orderDatas;
  },

  /*下单和付款*/
  pay: function () {
    if (!this.data.addressInfo) {
      wx.showToast({
        title: '请填写您的收货地址~',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    
    if (this.data.orderStatus == 0) {
      this._firstTimePay();
    } else {
      // this._oneMoresTimePay();
    }

  },

  /*第一次支付*/
  _firstTimePay: function () {
    if(this.data.onSub){
      return false;
    }
    this.data.onSub = true;
    wx.showLoading({
      title: '正在下单...',
    })
    var shops = [];
    var message = this.data.inputVal ? this.data.inputVal : '';
    var orderTOPayData = this.data.orderTOPayData;
    var len = orderTOPayData.length;
    for (let i = 0; i < len; i++) {
      var childLen = orderTOPayData[i].data.length;
      var cart_ids = [];
      for (let j = 0; j < childLen; j++) {
        cart_ids.push(parseInt(orderTOPayData[i].data[j].id));
      }
      var coupon_item_id = orderTOPayData[i].couponSelected ? orderTOPayData[i].couponSelected.id :''
      var obj = {
        'id': orderTOPayData[i].shop.id,
        'cart_ids': cart_ids,
        'citem_id': coupon_item_id,//优惠券id
        //'discount': 0,
        //'shipping_price': orderTOPayData[i].shipping_price,
        'mark': message,
        'buy_total': orderTOPayData[i].buy_total,
        'amount': this.data.amount
      };
      shops.push(obj);
    }

    var scoreMoney = 0;
    if (this.data.status){
      scoreMoney = this.data.scoreMoney;
    }
    var params = {
      'shops':shops,
      'type': this.data.type,
      'scoreMoney': scoreMoney,
      'aid': this.data.addressInfo.id,
      'real_amount': this.data.amount,
      'delivery_id': 0,
      'mark':message,
    }
    var that = this;
    //支付分两步，第一步是生成订单号，然后根据订单号支付
    order.doOrder(params, (data) => {
      this.data.onSub = false;
      wx.hideLoading();
      //订单生成成功
      if (data.status==1) {
        //更新订单状态
        that.data.fromCartFlag = false;
        //开始支付
        var params = { 'parent_id': data.msg}
        wx.navigateTo({
          url: 'payment?parent_sn=' + data.msg + '&entry=2'
        });
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
        // that._orderFail(data);  // 下单失败
      }
    });
  },

  // 获取留言信息
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  //选取优惠券弹窗
  couponSelect:function(e){
    var shop_index = e.currentTarget.dataset.index; //当前操作的商家索引
    this.data.shop_index = shop_index; //储存用于选取优惠券时是用于哪个商家的
    var coupon = this.data.orderTOPayData[shop_index].coupon;
    this.setData({
      couponList: coupon.enable,
      hiddenCoupon:false,
    })
  },
  
  //选中使用的优惠券
  couponConfirm:function(e){
    //记录选中的优惠券
    var index = e.currentTarget.dataset.index; //获取选中的优惠券id
    var shop_index = this.data.shop_index;
    this.data.orderTOPayData[shop_index].couponSelected = this.data.couponList[index];
    this.setData({
      couponName: this.data.couponList[index].coupon.name,
    })
    //计算使用优惠券后的金额
    this.couponCacu(shop_index);
    this.hiddenCoupon();
  },
  //使用优惠券的金额计算
  couponCacu: function (shop_index) {
    var shopData = this.data.orderTOPayData[shop_index];
    var coupon = shopData.couponSelected;
    if (coupon.coupon.use_type == 2) {//折扣券
      //单个店铺价格
      var goods_price = -1;
      if (coupon.coupon.product_limiter_id){ //指定商品打折
        shopData.data.forEach((item, index) => {
          if (item.product_id == coupon.coupon.product_limiter_id) {
            goods_price = item.sale_price_real;
          }
        })
      }else{ //全场打折
        shopData.data.forEach((item, index) => {
          if (item.shop_id == coupon.coupon.shop_id) {
            goods_price = shopData.sale_real_total;
          }
        })
      }
      if(goods_price < 0){
        //this.couponReset();
        wx.showToast({
          title: '该优惠券无法使用',
          icon: 'none',
          duration: 2000,
        })
        return false;
      }
      var discount = goods_price * ( coupon.coupon.use_money/100);
      discount = discount.toFixed(2);
      var rs = shopData.shopTotal_orign - discount;
      var discount_price = 'orderTOPayData[' + shop_index + '].discount';
      var price = 'orderTOPayData[' + shop_index + '].shopTotal';
      //总价
      var amount = this.data.amount_orign - discount;
      this.setData({
        [price]: rs,
        [discount_price]: discount,
        amount
      });
    } else if (coupon.coupon.use_type == 1) {//满减券
      var discount = coupon.coupon.use_money;
      //店铺小计
      var shop_total = shopData.shopTotal_orign - discount;
      var discount_price = 'orderTOPayData[' + shop_index + '].discount';
      var price = 'orderTOPayData[' + shop_index + '].shopTotal';
      //总价
      var amount = this.data.amount_orign - discount;
      this.setData({
        [price]: shop_total,
        [discount_price]: discount,
        amount
      });
    }
  },
  //不使用优惠券，还原原本的数据
  couponReset:function(){
    var shop_index = this.data.shop_index;
    this.data.orderTOPayData[shop_index].couponSelected = [];
    var discount = 0;
    var rs = this.data.orderTOPayData[shop_index].shopTotal_orign;
    var discount_price = 'orderTOPayData[' + shop_index + '].discount';
    var price = 'orderTOPayData[' + shop_index + '].shopTotal';
    //总价
    var amount = this.data.amount_orign;
    this.setData({
      
      [price]: rs,
      [discount_price]: discount,
      amount,
      couponName:''
    });
    this.hiddenCoupon();
  },
  //关闭优惠券弹窗
  hiddenCoupon: function (e) {
    this.setData({
      hiddenCoupon: true,
    })
  },
})